package com.sakiko.chat_image.controller;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import dev.langchain4j.community.model.dashscope.WanxImageModel;
import dev.langchain4j.data.image.Image;
import dev.langchain4j.model.output.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpResponse;

/**
 * projectName: com.sakiko.chat_image.controller
 *
 * @author: sakiko
 * time: 2025/8/24 15:41
 * description: https://help.aliyun.com/zh/model-studio/qwen-image-api
 */
@RestController
@Slf4j
public class WanxImageModelController {

    @Autowired
    private WanxImageModel wanxImageModel;

    // http://localhost:9006/image/create1
    @GetMapping("image/create1")
    public String createImageContent1(HttpResponse response) throws IOException {
        System.out.println("wanxImageModel = " + wanxImageModel);
        // 高阶 API 封装，简化开发逻辑
        Response<Image> imageResponse = wanxImageModel.generate("");
        URI url = imageResponse.content().url();
        System.out.println(url);
        saveIMG(url.toURL());
        return url.toString();
    }

    // http://localhost:9006/image/create2
    @GetMapping("image/create2")
    public String createImageContent3() throws IOException {
        String prompt = "近景镜头，18岁的中国女孩，古代服饰，圆脸，正面看着镜头，" +
                "cos(蜜雪冰城)雪王的服装，商业摄影，室外，电影级光照，半身特写，精致的淡妆，锐利的边缘。";
        //  低阶 API 封装，可以自由设置更多参数
        ImageSynthesisParam param = ImageSynthesisParam.builder()
                .apiKey(System.getenv("ALIBABA_BAILIAN_API_KEY"))
                .model(ImageSynthesis.Models.WANX_V1)
                .prompt(prompt)
                .style("<watercolor>")
                .n(1)
                .size("1024*1024")
                .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult res = null;

        try {
            System.out.println("--sync call please wait a moment--");
            res = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e) {
            throw new RuntimeException(e);
        }

        // 4. 从结果中提取图片URL（根据真实JSON结构，通过getUrl()获取）
        // 注意：如果你的SDK中该对象没有getUrl()，可查看SDK文档，可能是getImageUrl()等，核心是拿到JSON里的url字段值
        String imageOnlineUrl = res.getOutput().getResults().get(0).get("url");
        System.out.println("生成的图片在线URL：" + imageOnlineUrl);

        // 5. 调用保存方法（传入在线URL字符串）
        saveIMG(new URL(imageOnlineUrl));

        System.out.println("JsonUtils.toJson(res) = " + JsonUtils.toJson(res));
        return JsonUtils.toJson(res);
        /* console:
        --sync call please wait a moment--
        JsonUtils.toJson(res) = {"request_id":"6a228f9c-407f-993c-906c-92180aea3817","output":{"task_id":"77a63e0e-2be9-48bf-85c9-744fde758f8e","task_status":"SUCCEEDED","results":[{"url":"https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/1d/68/20250824/f52ecab8/499a4466-1464-42a7-9e70-9e64e5cd4888-1.png?Expires=1756109729&OSSAccessKeyId=LTAI5tQZd8AEcZX6KZV4G8qL&Signature=BmyTFFbVOW8kMFfnBfWAKzezIlY%3D"}],"task_metrics":{"TOTAL":1,"SUCCEEDED":1,"FAILED":0}},"usage":{"image_count":1}}
         */
    }


    private void saveIMG(URL url) throws IOException {
        // 创建保存目录
        String saveDir = "D:" + File.separator + "store install" + File.separator
                + "idea project" + File.separator + "java_langchain4j" + File.separator
                + "_06_langchain4j_chat_image" + File.separator + "src" + File.separator
                + "main" + File.separator + "resources" + File.separator + "static" + File.separator + "images" + File.separator;
        File dir = new File(saveDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成文件名
        String fileName = System.currentTimeMillis() + ".jpg";
        String filePath = saveDir + fileName;

        // 下载图片
        try (InputStream in = url.openStream();
             OutputStream out = new FileOutputStream(filePath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }
}
